package com.lwisniewski.pg.pulsehematometry.serial.main;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.log4j.Logger;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

public class SerialPortListener implements SerialPortEventListener {
	
	private final static Logger LOGGER = Logger.getLogger(SerialPortListener.class);

	private InputStream inputStream;
	private DataOutputStream outputStream;

	public SerialPortListener(InputStream inputStream, DataOutputStream outputStream) {
		this.inputStream = inputStream;
		this.outputStream = outputStream;
	}
	
	public void serialEvent(SerialPortEvent serialPortEvent) {
		
		int inputData;
		
		switch(serialPortEvent.getEventType()) {
		case SerialPortEvent.DATA_AVAILABLE:
			try {
				StringBuilder sb = new StringBuilder();
				while((inputData = inputStream.read()) > -1) {
	
					if(inputData == 13) {
						break;
					} if(inputData == 10) {
						break;
					}
					
					sb.append((char) inputData);
				}
				
				if(sb.length() > 0) {
					//trim it
					String pipelineMsg = new String(sb);
					pipelineMsg.trim();
					//write into inputstream
					LOGGER.debug(pipelineMsg);
					outputStream.writeUTF(pipelineMsg);
					
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		case SerialPortEvent.OUTPUT_BUFFER_EMPTY: 
			break;
		}
	}

}
